<template>
  <el-upload style="margin-top:8%" ref="clothImage" v-model:file-list="fileList"
             :limit="1" action="/api/wardrobePlus/upload_image/"
             :list-type="isMobile?'picture':'picture-card'"
             :auto-upload="false"
             :on-preview="handlePictureCardPreview"
             :on-exceed="handleExceed"
             :on-success="handleSuccess"
             :on-error="handleError"
             :before-upload="beforeAvatarUpload"
             :on-change="handleChange">

    <el-button v-if="isMobile">点击上传</el-button>
    <el-icon v-else>
      <Plus/>
    </el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img style="object-fit: contain;max-width: 100%" :src="dialogImageUrl" alt="Preview Image"/>
  </el-dialog>
</template>
<script lang="ts" setup>
import {ref, defineExpose, defineEmits} from 'vue'
import {Plus} from '@element-plus/icons-vue'

import type {UploadFile} from 'element-plus'

defineProps(["isMobile"])
const emit = defineEmits(["get_image_name"])
const clothImage = ref()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const fileList = ref([])

const handleExceed = (files) => {
  clothImage.value.clearFiles()
  const file = files[0]
  clothImage.value.handleStart(file)
}
const handleChange = (file: UploadFile) => {
  fileList.value.push(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
const submitUpload = () => {
  clothImage.value!.submit()
}
const handleSuccess = (res) => {
  if (res.code == -1) {
    ElMessage.error(res.message)
    clothImage.value.clearFiles()
  } else {
    emit("get_image_name", res.message)
    clothImage.value.clearFiles()
  }
}
const handleError = (res) => {
  ElMessage.error("前端图像上传失败:" + res)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile.type)
  if (rawFile.type === 'image/jpeg' || rawFile.type === 'image/png') {
    return true
  }
  ElMessage.error('上传的图片只能为PNG或者JPG格式！')
  return false
}
defineExpose({submitUpload})
</script>
